package com.jky.trial.common.poi;

import com.alibaba.fastjson.JSONObject;
import com.jky.trial.common.ExportUtil;
import com.jky.trial.common.Utils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class XlsUtil {

    /**
     * 前置条件
     * 1. 2007+以后模板
     *
     * @return
     */
    public OutputStream writeContent(String sheetName, List<Map> datas, ServletOutputStream outputStream) {

        // 创建一个workbook 对应一个excel应用文件
        XSSFWorkbook workBook = new XSSFWorkbook();
        // 在workbook中添加一个sheet,对应Excel文件中的sheet
        XSSFSheet sheet = workBook.createSheet(sheetName);
        ExportUtil exportUtil = new ExportUtil(workBook, sheet);
        XSSFCellStyle headStyle = exportUtil.getOriginHeaderStyle(IndexedColors.PALE_BLUE.index);
        XSSFCellStyle bodyStyle = exportUtil.getBodyStyle();
        // 构建表头
        XSSFRow headRow = sheet.createRow(0);
        headRow.setHeightInPoints((short) 30);
        XSSFCell cell = null;
        if (datas.size() > 0) { //  订单数大于 0
            Map map0 = datas.get(0);
            Set set = map0.keySet();
            Iterator iterator = set.iterator();
            int i = 0;
            while (iterator.hasNext()) {
                cell = headRow.createCell(i++);
                cell.setCellStyle(headStyle);
                cell.setCellValue(iterator.next().toString());
            }
            // 构建表体数据
            for (int j = 0; j < datas.size(); j++) {
                XSSFRow bodyRow = sheet.createRow(j + 1);
                Map data = datas.get(j);
                Iterator iterator1 = data.values().iterator();
                int k = 0;
                bodyRow.setHeightInPoints((short) 28);
                while (iterator1.hasNext()) {
                    cell = bodyRow.createCell(k++);
                    cell.setCellStyle(bodyStyle);
                    Object o = iterator1.next();
                    if (o == null) {
                        o = "";
                    }
                    cell.setCellValue(o.toString());
                }
            }
            for (int e = 0; e < set.size(); e++) {
                sheet.autoSizeColumn(e);
            }
        }

        try {
            workBook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public OutputStream writeDetail(JSONObject dataMap, ServletOutputStream outputStream) {

        // 创建一个workbook 对应一个excel应用文件
        XSSFWorkbook workBook = new XSSFWorkbook();
        Object[] keys = dataMap.keySet().toArray();
        for (Object keyItem : keys) {
            String key = keyItem.toString();
            // 在workbook中添加一个sheet,对应Excel文件中的sheet
            XSSFSheet sheet = workBook.createSheet(key);
            ExportUtil exportUtil = new ExportUtil(workBook, sheet);

            List list = (List) dataMap.get(key);
            if (list.size() > 0) { //  订单数大于 0
                // 构建表体数据
                for (int j = 0; j < list.size(); j++) {
                    XSSFRow row = null;
                    XSSFCellStyle style = null;
                    if (j == 0) {
                        // 构建表头
                        row = sheet.createRow(j);
                        style = exportUtil.getOriginHeaderStyle(IndexedColors.PALE_BLUE.index);
                    } else {
                        //构建表体
                        row = sheet.createRow(j);
                        style = exportUtil.getBodyStyle();
                    }
                    row.setHeightInPoints((short) 28);
                    listToCell((List<String>) list.get(j), row, style, sheet);
                }
                List list1 = (List<String>) list.get(0);
                for (int j = 0; j < list1.size(); j++) {
                    sheet.autoSizeColumn(j);
                }
            }
        }


        try {
            workBook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 创建并赋值cell
     *
     * @param list
     * @param row
     */
    public void listToCell(List<String> list, XSSFRow row, XSSFCellStyle style, XSSFSheet sheet) {
        for (int i = 0; i < list.size(); i++) {
            Cell cell = row.createCell(i);
            cell.setCellStyle(style);
            cell.setCellValue(list.get(i).toString());
        }
    }


    public void setResponseHeader(HttpServletResponse response, HttpServletRequest request, String fileName) {
        response.setContentType("application/binary;charset=UTF-8");
        fileName = Utils.processFileName(request, fileName);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + (new SimpleDateFormat("yyyy-MM-dd").format(new Date())) + ".xlsx\"");// 组装附件名称和格式
        response.setCharacterEncoding("UTF-8");
    }

    public String genAttachmentFileName(String cnName, String defaultName) {
        try {
            cnName = new String(cnName.getBytes("gb2312"), "ISO8859-1");
        } catch (Exception e) {
            cnName = defaultName;
        }
        return cnName;
    }


    public OutputStream exportTxt(HttpServletResponse response, String text) {
        response.setCharacterEncoding("utf-8");
        //设置响应的内容类型
        response.setContentType("text/plain");
        //设置文件的名称和格式
//        response.addHeader("Content-Disposition", "attachment;filename="
//                + genAttachmentFileName("文件名称", "JSON_FOR_UCC_")//设置名称格式，没有这个中文名称无法显示
//                + ".txt");
        BufferedOutputStream buff = null;
        ServletOutputStream outStr = null;
        try {
            outStr = response.getOutputStream();
            buff = new BufferedOutputStream(outStr);
            buff.write(text.getBytes("UTF-8"));
            buff.flush();
            buff.close();
        } catch (Exception e) {
            System.out.println(e);
            //LOGGER.error("导出文件文件出错:{}",e);
        } finally {
            try {
                buff.close();
                outStr.close();
            } catch (Exception e) {
                //LOGGER.error("关闭流对象出错 e:{}",e);
            }
        }
        return null;
    }
}
